package handler;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import handler.post.TestButton;
import org.jaaksi.commondemo.R;
import org.jaaksi.commondemo.util.LogUtil;

/**
 * 创建时间：2017年12月05日18:25 <br>
 * 作者：fuchaoyang <br>
 * 描述：
 */

public class TestHandlerActivity extends Activity {

  private ThreadHandler mThreadHandler;
  private HandlerThread mHandlerThread;

  private TestButton mBtn;

  @Override protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_handler);
    mBtn = (TestButton) findViewById(R.id.btn);
    // 这个会先执行view的 onAttachedToWindow onSizeChanged之后再执行post，然后执行onDraw
    mBtn.post(new Runnable() {
      @Override public void run() {
        int width = mBtn.getWidth();
        LogUtil.e("tag", "view post:getWidth()=" + width);
      }
    });
    // 下面这个会先于view的post执行
    new Handler().post(new Runnable() {
      @Override public void run() {
        LogUtil.e("tag", "handler post");
      }
    });

    String threadName = "test1";
    mHandlerThread = new HandlerThread(threadName) {
      @Override protected void onLooperPrepared() {
        String name = Thread.currentThread().getName();
      }
    };
    // fixme 这个线程start之后什么时候结束呢
    mHandlerThread.start();
    mThreadHandler = new ThreadHandler(mHandlerThread.getLooper());
    mThreadHandler.sendEmptyMessage(1);

    new Handler().postDelayed(new Runnable() {
      @Override public void run() {
        System.out.println("isAlive after quit = " + mHandlerThread.isAlive());
        mThreadHandler.sendEmptyMessage(2);
      }
    }, 3000);
  }

  public final class ThreadHandler extends Handler {
    public ThreadHandler(Looper looper) {
      super(looper);
    }

    @Override public void handleMessage(Message msg) {
      // 运行在子线程中，因为这里的Looper传递的是子线程的Looper
      String name = Thread.currentThread().getName();
      System.out.println("msg.what = " + msg.what);
      // 这个结束了，线程才会结束吗？子线程的Looper不再处理消息时该线程终止？
      try {
        Thread.sleep(1000);
        // 休眠1s后，调用HandlerThread的quit方法
        System.out.println("isAlive before quit = " + mHandlerThread.isAlive());
        mHandlerThread.quit();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }

  private void createThreadHandler() {
    // 子线程创建handler的步骤
    new Thread(new Runnable() {
      @Override public void run() {
        // 1.Looper.prepare();
        Looper.prepare();
        // 2.创建Handler
        Handler handler = new Handler();
        // 3.调用loop方法激活
        Looper.loop();
      }
    }).start();
  }

  // Looper伪代码
  /*public class Looper {
    static final ThreadLocal<android.os.Looper> sThreadLocal = new ThreadLocal<android.os.Looper>();
    private static android.os.Looper sMainLooper;  // guarded by Looper.class

    final MessageQueue mQueue;
    final Thread mThread;

    private Looper(boolean quitAllowed) {
      // Looper被创建的时候，创建MessageQueue并绑定当前线程
      mQueue = new MessageQueue(quitAllowed);
      mThread = Thread.currentThread();
    }

    public static void prepare() {
      prepare(true);
    }

    private static void prepare(boolean quitAllowed) {
      // 创建 Looper
      sThreadLocal.set(new android.os.Looper(quitAllowed));
    }

    public static void loop() {
      // Lopper去轮询 MessageQueue，阻塞不停的从消息队列中取出消息然后处理，一直阻塞
      final android.os.Looper me = myLooper();
      final MessageQueue queue = me.mQueue;
      for (; ; ) {
        Message msg = queue.next(); // might block
        if (msg == null) {
          // No message indicates that the message queue is quitting.
          return;
        }
        // xxx 处理分发消息
        msg.target.dispatchMessage(msg);
      }
    }
  }*/

  // android main 函数入口伪代码
  /*public static void main(String[] args) {
    ....

    //创建Looper和MessageQueue对象，用于处理主线程的消息
    Looper.prepareMainLooper();

    //创建ActivityThread对象
    ActivityThread thread = new ActivityThread();

    //建立Binder通道 (创建新线程)
    thread.attach(false);

    Looper.loop(); //消息循环运行
    throw new RuntimeException("Main thread loop unexpectedly exited");
  }*/
}
